<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 4月9日
 * Time: 13:58
 * 这个不同于dofun，这个将所有操作全都独立出来。后续对接新offer，建议以此为模板。
 */
namespace app\api\controller;

use app\api\model\InfimobData;
use app\api\controller\Offer;

class Infimob
{
    private $app_id = 103;
    private $app_key = '330a2171bc59ab3cf0ea96388a3e5458';

    public function index()
    {
        $url = 'http://apiw.infimob.com/index.php?m=advert&p=getoffer&app_id='.$this->app_id.'&app_key='.$this->app_key.'&platform=ios&countries=US,UK,JP,KR,TW,CN&pagesize=10';
        $str = json_decode(file_get_contents($url),true);
        dump($str);
    }

    /*
     * 获取offer数据
     */
    public function getData()
    {
        $data_mod = new InfimobData;

        $limit = 200;//获取条数
        $url = 'http://apiw.infimob.com/index.php?m=advert&p=getoffer&app_id='.$this->app_id.'&app_key='.$this->app_key.'&platform=ios&countries=US,UK,JP,KR,TW,CN&pagesize='.$limit;

        set_time_limit(0);
        echo '开始:'.date("H:i:s")."<br />";
        $get_str = file_get_contents($url);
        $get_content = json_decode($get_str,true);//dump($get_content);exit;
        echo '获取数据：'.date("H:i:s")."<br />";

        $i = $j = $m = 0;
        $new_offerids = $update_offerids = '';
        $all_offerids = $update_data = $insert_data = array();

        if($get_content['status'] == 'success'){
            $data_arr = $get_content['offers'];
            if(!empty($data_arr)){
                //轮询所有数据
                foreach($data_arr as $k=>$v){
                    $all_offerids[] = $v['id'];
                    //去除多余数据
                    if(isset($v['network'])){
                        unset($v['network']);
                    }
                    if(isset($v['networkid'])){
                        unset($v['networkid']);
                    }
                    if(isset($v['ecpc'])){
                        unset($v['ecpc']);
                    }
                    if(!empty($v['images'])){
                        $v['images'] = json_encode($v['images']);
                    }

                    if(empty($v['preview_url'])){
                        $v['preview_url'] = ($v['platform'] == 'ios' && !empty($v['packet_name'])) ? 'https://itunes.apple.com/cn/app/id'.$v['packet_name'] : '';
                    }

                    $v['minOS'] = format_ver($v['minOS']);

                    $offer_info = $data_mod->find($v['id']);
                    if(!empty($offer_info)){ //该offer已经存在,对比信息是否有更新
                        $diff_arr = array();
                        $offer_info = $offer_info->toArray();

                        if($offer_info['price'] != $v['price']){ //如果价格有更新，则获取更新数据
                            $diff_arr['update_time'] = time();
                            $diff_arr['id'] = $v['id'];
                            $diff_arr['price'] = $v['price'];
                            $diff_arr['offer_status'] = 2;// 2表示等待更新
                            $update_data[] = $diff_arr;
                            $i++;//更新数
                            $update_offerids .= $v['id'].',';//记录日志用的
                        } else {
                            $j++;//已有数
                        }


                    } else { //该offer不存在,获取新增数据
                        $time = time();
                        $v['update_time'] = $time;
                        $v['create_time'] = $time;
                        $insert_data[] = $v;

                        $new_offerids .=$v['id'].',';//记录日志用的

                        $m++;//新增数
                    }
                }
            }
        }

        echo '循环数据：'.date("H:i:s")."<br />";
        //新增记录

        if(!empty($insert_data))
        {
            $insert_res = $data_mod->saveAll($insert_data,false);
        }

        //更新记录
        if(!empty($update_data))
        {
            $update_res = $data_mod->isUpdate()->saveAll($update_data);
        }


        //将本次没有获取的单子全部做下线处理
        $data_mod->whereNotIn('id',$all_offerids)->where(array('offer_status'=>1))->update(array('update_time'=> time(),'offer_status'=> 3));
        //记录日志
        save_apilog('add_offersId:'.$new_offerids,'infimob');
        save_apilog('update_offersId:'.$update_offerids,'infimob');

        echo '插入数据：'.date("H:i:s")."<br />";

        echo '更新数据:'.$i."<br />";
        echo '已有数据:'.$j."<br />";
        echo '新增数据:'.$m."<br />";
    }


    /*
     * 推送offer
     */
    public function postOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 47;
        $data_mod = new InfimobData;


        //$info = $data_mod->limit(1)->find()->toArray();
        $insert_data = $data_mod->where(array('offer_id'=>0,'offer_status'=>0))->select()->toArray();
        //dump($insert_data);exit;
        if(empty($insert_data))
        {
            echo 'No offers add';
            exit;
        }
        foreach($insert_data as $info){
            //0.2以下的单子不导入
            /*if($info['price'] < 0.2) {
                continue;
            }*/

            $search_arr = array(
                '{clickid}',
                '{gaid}',
                '{android}',
                '{idfa}',
                '{subid}'
            );
            $replace_arr = array(
                '{click_id}',
                '{google_aid}',
                '{android_id}',
                '{ios_idfa}',
                '{aff_id}'
            );
            $destination_url = str_replace($search_arr,$replace_arr,$info['tracklink']);

            $countries = explode(',',$info['countries']);
            $os_version = empty($info['minOS']) ? 0 : (($info['platform'] == 'ios' && $info['minOS'] < 5.0) ? 0 : $info['minOS']);

            $param = array(
                'name' => $info['name'],
                'preview_url' => empty($info['preview_url']) ? '' : $info['preview_url'],
                //'destination_url' => 'http://ads.dofunapps.com/acs.php?sid=6362&adid=7792014',
                'destination_url' => $destination_url,
                'description' => $info['description'],
                'offer_id' => $info['id'],
                'price' => $info['price'],
                'os' => $info['platform'],
                'os_version' => $os_version,
                'country' => $countries,
                'day_cap' => $info['day_cap'],
                'status' => 1,
            );
            $res = $offer_obj->addOffer($param,$advertiser_id);
            //dump($res);
            if($res['code'] != 0){
                save_apilog('post_fail:'.json_encode($res),'infimob');
                continue;
            }
            //dump($param);dump($res);exit;
            //dump($res);
            $update_data = array('offer_id'=> $res['data']['offer']['id'],'offer_status'=> 1);
            //$data_mod->save($update_data,array('id'=> $info['id']));
            $data_mod->where(array('id'=> $info['id']))->update($update_data);
        }
        //dump($info);



    }

    /*
     * 更新offer
     */
    public function updateOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 47;
        $data_mod = new InfimobData;
        $update_data = array();

        $update_offerid_list = $data_mod->where(array('offer_id'=>array('>',0),'offer_status'=>2))->field('id,price,offer_id')->select()->toArray();//dump($update_offerid_list);exit;
        if(empty($update_offerid_list))
        {
            echo 'No offers update';
            exit;
        }
        foreach($update_offerid_list as $info){

            $offer_res = $offer_obj->updateOfferPrice($info['offer_id'],$info['price']);
            if($offer_res['code'] != 0)
            {
                save_apilog('update_offer_price:'.json_encode($offer_res),'infimob');
            }
            //dump($res);
            $update_data[] = array('id'=> $info['id'],'offer_status'=> 1);
        }
        //dump($info);


        $res = $data_mod->isUpdate()->saveAll($update_data);

    }

    /*
     * 更新offer状态
     */
    public function updateOfferStatus()
    {
        //$ids = array(127);
        $offer_obj = new Offer();

        $data_mod = new InfimobData;
        //将单子下线
        $where = array(
            'offer_status'=> 3,
        );
        $list = $data_mod->field('offer_id')->where($where)->limit(100)->select()->toArray();
        $ids = array();
        foreach($list as $id){
            $ids[] = $id['offer_id'];
        }
        if(!empty($ids)){
            $res = $offer_obj->pausedOffer($ids);
            if($res['code'] != 0){
                save_apilog('paused_offer:'.json_encode($res),'infimob');
            }
            $data_mod->whereIn('offer_id',$ids)->update(array('offer_status'=> -1));
        }


    }
}